# A simple DSL for creating SVG images on the fly. Built on top of Builder
# (http://builder.rubyforge.org/).
#
# == Usage example
#
# image = SvgImage.new(400, 200) do |canvas|
#   canvas.g(:stroke => "black", "stroke-width" => 5) do
#     canvas.rect(:x => 0, :y => 0, :width => 400, :height => 200,
#                 :fill => "none")
#   end
#   canvas.text("Some text", :x => 100, :y => 120)
# end
# puts image.to_svg
#
class SvgImage

  attr_accessor :width, :height

  def initialize(options, &block)
    @options = options
    @block  = block
  end

  def to_svg
    builder = Builder::XmlMarkup.new(:indent => 2)
    builder.instruct!(:xml, :standalone => "no")
    builder.declare!(:DOCTYPE, :svg, :PUBLIC, "-//W3C//DTD SVG 1.1//EN",
                     "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd")
    builder.svg(@options.merge(:version => 1.1,
                               :xmlns => "http://www.w3.org/2000/svg",
                               "xmlns:xlink" => "http://www.w3.org/1999/xlink")) do
      @block.call(builder)
    end
    builder.target!
  end
end
